<?php
namespace Kuoqi\Curl;
class Request{
	
	private $curl = null;
	private $resource = null;
	private $method = '';
	
	public function __construct($curl){
		$this->curl = $curl;
		$this->resource = $curl->resource;
		$this->method = $curl->getMethod();
		//如果有自定义输入，则跳过这些序列化的配置信息
		$curl->isCustom||$this->output($this->method);
	}
	
	public function output($type){
		switch($type){
			case 'POST':return $this->requestPost();break;
			case 'JSON':return $this->requestJson();break;
			case 'GET':return $this->requestGet();break;
			case 'XML':return $this->requestXml();break;
			default:return;
		}
	}
	
	final function requestJson(){
		$this->curl->method = 'POST';
		$this->curl->headinfo = array('Content-Type:application/json');
		if(PHP_VERSION>='5.5'){
			$params = json_encode($this->curl->params,JSON_UNESCAPED_UNICODE);
		}else{
			$params= json_encode($this->curl->params);
		}
		curl_setopt($this->resource, CURLOPT_POST, true);
		curl_setopt($this->resource, CURLOPT_POSTFIELDS,$params);		
	}
	
	final function requestPost(){
		$params = $this->curl->getParams();
		if($this->curl->server_language=='java'){
			$params = Tools::arr2datajava($params);
		}else{
			$params = Tools::arr2datapost($params);
		}
		curl_setopt($this->resource,CURLOPT_POST,true);
		curl_setopt($this->resource,CURLOPT_POSTFIELDS,$params);	
	}

    /**
     * createby kuoqi at 2022/10/22 12:47 xml的方式使用请求
     */
	final function requestXml(){
        $params = $this->curl->getParams();
        $this->curl->method = 'POST';
        $this->curl->headinfo = array('Content-Type: application/json');
        curl_setopt($this->resource,CURLOPT_POST,true);
        curl_setopt($this->resource,CURLOPT_POSTFIELDS,$params);
    }
	
	//
	final function requestGet(){
		$params = $this->curl->getParams();
		if($params){
			if($this->curl->server_language=='java'){
				$params = Tools::arr2datajava($params);
			}else{
				$params = Tools::arr2datapost($params);
			}
			
			$tmp = array();
			foreach($params as $k=>$v){
				$tmp[] = $k.'='.$v;
			}
			$params = $tmp;
		}
		//这个要去掉？的部分，要进行处理了喔
		//去掉画蛇添足的部分
		//$this->curl->curl = \Kuoqi\Route::url($this->curl->curl,$params,true);
		//实现真实的代码信息
		//最终放置的地方：$this->curl->curl;
		if($params){
			//这是有参数的时候，这个时候才需要处理
			//todo--这里还是有问题，遇到再改	
			$query = implode('&',$params);
			$urlarr = parse_url($this->curl->curl);
			if(isset($urlarr['query'])){
				//只有这种情况才需要处理query的信息
				$query = $urlarr['query'];
				throw new \Kuoqi\Error('这种情况待完善');
			}else{
				$this->curl->curl = $this->curl->curl.'?'.$query;
			}
		}else{
			//这个时候是不需要做任何处理的，本来$this->curl->curl就是对的	
		}
	}
}